package com.jinyi.wwdeng.ui.steps.act

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.view.Gravity
import android.view.View
import androidx.core.content.ContextCompat
import com.jinyi.base.utils.ActivityStackManager
import com.jinyi.base.utils.BarUtils
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActOcrCropBinding
import com.jinyi.wwdeng.pro.ProAct
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_CONTENT_TYPE
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_FILE_PATH
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_ORC_FRONT
import com.jinyi.wwdeng.ui.steps.act.OcrUploadAct.Companion.KEY_ORC_TYPE
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/22 15:50
 * @Annotation：图片剪裁
 */
class OcrCropAct: ProAct() {

    lateinit var binding: ActOcrCropBinding

    private var outputFile: File? = null

    override fun getRootView(): View {
        binding = ActOcrCropBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setTitleBarColor(ContextCompat.getColor(this, R.color.color_353535))
        setBackBtnRes(R.mipmap.pic_back_white_icon)
        setRightBtnRes(R.mipmap.pic_kefu_white_icon)
        setTextTitle(getString(R.string.confirmer_le_compte))
        setTextTitleColor(ContextCompat.getColor(this, com.jinyi.lib_base.R.color.color_ffffff))
        setTextTitleGravity(Gravity.CENTER)
        BarUtils.setStatusBarLightMode(this, false)
    }

    override fun initListener() {
        //返回
        binding.btnCancel.setOnClickListener {
            finish()
        }
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"OcrCrop ${getOcrTypeString()} Page")
        }
        //旋转
        binding.btnRotate.setOnClickListener {
            binding.cropView.rotate(90)
        }
        //确认
        binding.btnConfirm.setOnClickListener {
            doConfirmResult()
        }
    }

    override fun initData() {
        val bundle = intent.extras
        val outputPath = bundle!!.getString(KEY_FILE_PATH)
        binding.cropView.setFilePath(outputPath)

        //1相机 2相册
        //相机outputFile是直接修改原图片   相册outputFile需要创建新文件
        val contentType = bundle!!.getInt(KEY_CONTENT_TYPE)
        if (contentType == 1 && outputPath != null){
            outputFile = File(outputPath)
        }
    }

    /**
     * 获取证件类型  1身份证  2护照  3驾驶证
     */
    private fun getOcrType(): Int{
        val bundle = intent.extras
        if (bundle != null){
            return bundle.getInt(KEY_ORC_TYPE,1)
        }
        return 1
    }

    /**
     * 获取正反面
     */
    private fun getOcrFront(): Boolean{
        val bundle = intent.extras
        if (bundle != null){
            return bundle.getBoolean(KEY_ORC_FRONT,true)
        }
        return true
    }

    /**
     * 获取证件类型
     * IdCard  Passport DriverLicense
     */
    private fun getOcrTypeString(): String{
        when(getOcrType()){
            1 -> {
                return "IdCard"
            }
            2 -> {
                return "Passport"
            }
            else -> {
                return "DriverLicense"
            }
        }
    }

    /**
     * 确认
     */
    private fun doConfirmResult() {
        if (outputFile == null) {
//            val filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/";
            val filePath = App.instance().filesDir.absolutePath
            outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
        }
        Thread{
            try {
                val rect = binding.cropMaskView.frameRect
                val croppedBitmap = binding.cropView.crop(rect)
                val fileOutputStream = FileOutputStream(outputFile)
//                val bitmap = (displayImageView.getDrawable() as BitmapDrawable).bitmap
                croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
                fileOutputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            //刷新图库
            sendBroadcast(Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", Uri.fromFile(outputFile)))
            //需要关闭相机页面
            ActivityStackManager.finishActivity(OcrCameraAct::class.java)

            val bundle = Bundle()
            bundle.putString(KEY_FILE_PATH,outputFile!!.absolutePath)
            bundle.putInt(KEY_ORC_TYPE,getOcrType())//证件类型  1身份证  2护照  3驾驶证
            bundle.putBoolean(KEY_ORC_FRONT,getOcrFront())//是否是正面
            onIntent(OcrUploadAct::class.java,bundle)
            finish()
        }.start()
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_OCR_CAMERA_CONFIRM_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_OCR_CAMERA_CONFIRM_END,"")
    }
}